<template>
  <div id="app">
    <v-app>
      <div class="setting" @click="setNetwork">
        <v-icon size="20">{{ mdiCog }}</v-icon>
      </div>
      <v-container class="login-box">
        <v-row class="ma-0 pa-0">
          <v-col cols="12" class="py-0">
            <div class="d-flex justify-end align-center login-img">
              <img src="../../assets/img/epichust-le.png" />
            </div>
          </v-col>
        </v-row>
        <v-row class="ma-0 pa-0 flex-column px-2 mt-3" style="width: 85%">
          <v-text-field
            color="#193690"
            ref="username"
            v-model="user.account"
            :label="$t('base.username')"
            :prepend-icon="mdiAccountCircle"
            :error-messages="usernameText"
          ></v-text-field>
          <v-text-field
            color="#193690"
            ref="password"
            v-model="user.password"
            v-on:keyup.enter="signIn"
            :label="$t('base.password')"
            :prepend-icon="mdiLock"
            :append-icon="visibility ? mdiEye : mdiEyeOff"
            @click:append="() => (visibility = !visibility)"
            :error-messages="passwordText"
            :type="visibility ? 'text' : 'password'"
          ></v-text-field>
        </v-row>
        <v-row class="ma-0 pa-0">
          <div class="d-flex justify-space-between align-center check-box">
            <!-- <v-btn text ref="selectLangs" @click="langsOpen = !langsOpen">
              语言/langs：{{ selectLang }}
            </v-btn> -->
            <!-- <v-checkbox
              color="#193690"
              class="remember-checkbox mt-0"
              hide-details
              v-model="user.remember"
              :label="$t('base.remember_me')"
              style="
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              "
            >
            </v-checkbox> -->
          </div>
        </v-row>
        <v-row class="ma-0 pa-0">
          <v-col cols="12">
            <v-btn
              rounded
              class="login-btn"
              style="letter-spacing: 2px"
              block
              color="primary"
              @click="signIn()"
              :loading="loginLoading"
              >{{ $t("base.sign_in") }}
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
      <v-dialog
        v-model="openFullscreen"
        transition="slide-y-reverse-transition"
        width="360"
      >
        <v-appbar
          color="primary"
          :title="$t('message.message_login_update_down')"
        >
        </v-appbar>
        <div class="download-modal">
          <div class="d-flex linear-progress">
            <v-progress-linear :value="linear" height="18" color="green">
            </v-progress-linear>
          </div>
          <div style="margin-top: 10vh">
            {{ $t("message.message_login_update_downing") }}
          </div>
          <div class="percent">{{ linear }}%</div>
        </div>
      </v-dialog>
      <!-- 选择工厂 -->
      <v-dialog
        :title="$t('message.message_login_choose_factory')"
        width="360"
        max-width="500"
        v-model="openFullscreen"
      >
        <v-list>
          <v-list-item :key="index" v-for="(factory, index) in factoryList">
            <mu-list-item-content>
              <v-radio-group v-model="factoryCode">
                <v-radio
                  :value="factory.siteCode"
                  :label="factory.siteName + '(' + factory.siteCode + ')'"
                ></v-radio>
              </v-radio-group>
            </mu-list-item-content>
          </v-list-item>
        </v-list>
        <v-btn text color="primary" @click="closeSimpleDialog()">{{
          $t("base.confirm")
        }}</v-btn>
      </v-dialog>
      <!-- 多语言 -->
      <!-- 报错弹框 -->
      <v-dialog
        :title="$t('message.message_login_networkerror')"
        width="360"
        max-width="500"
        :esc-press-close="false"
        :overlay-close="false"
        v-model="openAlert"
      >
        {{ $t("message.message_login_networktip") }}
        <v-btn text color="primary" @click="networkerror_disagree">{{
          $t("base.cancel")
        }}</v-btn>
        <v-btn text color="primary" @click="networkerror_agree">{{
          $t("base.confirm")
        }}</v-btn>
      </v-dialog>
      <!-- 版权信息 -->
      <div class="login-copyright">
        <p style="margin-bottom: 0px; font-size: 12px">
          艾普工华科技（武汉）有限公司
        </p>
        Copyright&copy;2012-2022
      </div>
    </v-app>
  </div>
</template>

<script>
import business from "@/utils/business_wms.js";
import { mdiAccountCircle, mdiLock, mdiEye, mdiEyeOff, mdiCog } from "@mdi/js";
// load css
import _ from "lodash";
import Storage from "@/utils/storage.js";
import Static from "@/utils/static.js";
import wms from "@/utils/business_wms";
export default {
  name: "login",

  data: () => {
    return {
      // icon
      mdiAccountCircle: mdiAccountCircle,
      mdiLock: mdiLock,
      mdiEye: mdiEye,
      mdiEyeOff: mdiEyeOff,
      mdiCog: mdiCog,
      //
      user: {
        account: localStorage.getItem("account"),
        password: localStorage.getItem("password"),
        remember: true,
      },
      visibility: false,
      usernameText: "",
      passwordText: "",
      loginLoading: false,
      openFullscreen: false,
      linear: 0,
      openSimple: false,
      factoryList: [],
      factoryCode: "",
      langs: [
        { label: "中文", value: "cn", selected: true },
        { label: "English", value: "en", selected: false },
      ],
      langsOpen: false, // 多语言选项
      trigger: null,
      openAlert: false,
    };
  },
  computed: {
    selectLang() {
      let _selectLang = this.langs.find((v) => v.selected);
      return _selectLang.label;
    },
  },
  methods: {
    // 弹出设置网络
    setNetwork() {
      if (window.navigator.userAgent.toLowerCase().includes("apicloud")) {
        window.api.openWin({
          name: "network",
          url: "./network.html",
          pageParam: {
            name: "",
          },
        });
      } else {
        this.$root.api.api.openWin({
          name: "network",
          url: "./network.html",
          pageParam: {
            name: "",
          },
        });
      }
    },
    signIn() {
      if (!this.user.account) {
        this.usernameText = this.$i18n.t("message.message_login_inputusername");
        this.$refs.username.focus();
        return false;
      } else {
        this.usernameText = "";
      }
      if (!this.user.password) {
        this.passwordText = this.$i18n.t("message.message_login_inputpassword");
        this.$refs.password.focus();
        return false;
      } else {
        this.passwordText = "";
      }
      this.loginLoading = true;
      business
        .login({ url: "/login", data: this.user })
        .then((res) => {
          console.log(res);
          if (res.status == 200 && res.data.code == 200) {
            Storage.setItem("token", res.data.data.token);
            business
              .login({ url: "/login/info", data: this.user })
              .then((ret) => {
                if (ret.status == 200 && ret.data.code == 200) {
                  console.log(ret, 111111);
                  localStorage.setItem("userName", ret.data.data.userName);
                  localStorage.setItem("account", this.user.account);
                  localStorage.setItem("password", this.user.password);
                  Storage.setObject("loginConfig", ret.data.data);
                  let lang = Storage.getObject("lang");
                  let mainPageParams = lang
                    ? Static["mainPageParams_" + lang.value]
                    : Static["mainPageParams_cn"];
                  if (
                    window.navigator.userAgent
                      .toLowerCase()
                      .includes("apicloud")
                  ) {
                    window.api.openTabLayout(mainPageParams);
                  } else {
                    this.$root.api.api.openTabLayout(mainPageParams);
                  }
                }
              });
          } else {
            this.$toast(this.$i18n.t("message.message_login_networkerror"), {
              showClose: true,
              timeout: 60000,
              color: "error",
            });
          }
        })
        .catch((err) => {
          console.log("==================");
          this.$toast(
            this.$i18n.t("message.message_login_networkerror") +
              ":" +
              JSON.stringify(err),
            {
              showClose: true,
              timeout: 60000,
              color: "error",
            }
          );
          console.log(JSON.stringify(err));
        });
      // .finally(() => {
      this.loginLoading = false;
      // });
    },
    closeSimpleDialog() {
      if (!this.factoryCode) {
        this.$toast(this.$i18n.t("message.message_login_choosefactory"), {
          color: "warning",
        });
        return false;
      }
      let that = this;
      let resObj = _.find(this.factoryList, function (obj) {
        return obj.siteCode == that.factoryCode;
      });
      Storage.setObject("multipleObj", resObj);
      this.openSimple = false;
      if (!Storage.getObject("lang")) {
        Storage.setObject("lang", {
          label: "中文",
          selected: false,
          value: "cn",
        });
      }
      let lang = Storage.getObject("lang");
      let mainPageParams = lang
        ? Static["mainPageParams_" + lang.value]
        : Static["mainPageParams_cn"];

      if (window.navigator.userAgent.toLowerCase().includes("apicloud")) {
        window.api.openTabLayout(mainPageParams);
      } else {
        this.$root.api.api.openTabLayout(mainPageParams);
      }
    },
    async getFactory() {
      try {
        let res = await business.getFactory();
        if (res.status == 200 && res.data.erroCode == 0) {
          this.factoryList = res.data.data;
          this.openSimple = true;
        } else {
          this.$toast(JSON.stringify(res.data.msg), {
            color: "error",
          });
        }
      } catch (error) {
        this.$toast(JSON.stringify(error), {
          color: "error",
        });
      }
    },
    changeLang(lang) {
      console.log(lang);
      this.$i18n.locale = lang.value;
      Storage.setObject("lang", lang);
      this.langs = this.langs.map((item) => {
        item.selected = item.value == lang.value;
        return item;
      });
      this.langsOpen = !this.langsOpen;
    },
    openAlertDialog() {
      this.openAlert = true;
    },
    networkerror_disagree() {
      this.openAlert = false;
    },
    networkerror_agree() {
      this.openAlert = false;
      if (window.navigator.userAgent.toLowerCase().includes("apicloud")) {
        window.api.openWin({
          name: "network",
          url: "./network.html",
          pageParam: {
            name: "",
          },
        });
      } else {
        this.$root.api.api.openWin({
          name: "network",
          url: "./network.html",
          pageParam: {
            name: "",
          },
        });
      }
    },
  },
  mounted() {
    let that = this;
    const myVersion = window.api.appVersion;
    let userObj = Storage.getObject("user");
    console.log(myVersion);
    if (userObj != null) {
      let isRemeber = userObj.remember;
      if (isRemeber) {
        this.user.account = userObj.account;
        this.user.password = userObj.password;
        this.user.remember = userObj.remember;
      }
    }
    //设置语言选项
    // let theLang = Storage.getObject("lang");
    // if (theLang) {
    //   this.langs = this.langs.map((item) => {
    //     item.selected = item.value == theLang.value;
    //     return item;
    //   });
    // }
    // this.trigger = this.$refs.selectLangs.$el;

    wms
      .get({
        url: "/common/getAppVer",
        data: { oldVer: window.api.appVersion },
      })
      .then((res) => {
        console.log(JSON.stringify(res));
        if (res.status == 200 && res.data.code == 200) {
          let fs = window.api.require("fs");
          if (!fs) {
            return true;
          }

          fs.exist({ path: "fs://EpichustApp.apk" }, function (ret, err) {
            if (ret.exist) {
              fs.remove(
                {
                  path: "fs://EpichustApp.apk",
                },
                function (ret, err) {
                  if (ret.status) {
                    console.log(err);
                  }
                }
              );
            } else {
              // console.log(err);
            }
          });
          let reslut = res.data.data.split(":");
          console.log(reslut);
          if (reslut[0] == "S") {
            let serverVersion = Number(reslut[1].replace(/\./g, ""));
            let thisVersion = Number(myVersion.replace(/\./g, ""));
            if (serverVersion > thisVersion) {
              window.api.confirm(
                {
                  title: "更新提示",
                  msg: "要更新程序吗?",
                  buttons: ["确定", "取消"],
                },
                function (ret, err) {
                  let index = ret.buttonIndex;
                  if (index == 1) {
                    this.openFullscreen = true;
                    let network = Storage.getObject("network");
                    let selectedIndex = Storage.getObject("selectedIndex");
                    network = network[selectedIndex];
                    let downloadUrl = `http://${network.ip}:${network.port}/${network.appName}/common/download/app`;
                    console.log(downloadUrl);
                    window.api.download(
                      {
                        url: downloadUrl,
                        report: true,
                        cache: true,
                        allowResume: true,
                        savePath: "fs://EpichustApp.apk",
                      },
                      function (ret, err) {
                        console.log(JSON.stringify(ret));
                        if (ret && ret.state == 0) {
                          /* 下载进行中 */
                          that.linear = ret.percent;
                        }
                        if (ret && ret.state == 1) {
                          /* 下载完成 */
                          that.linear = ret.percent;
                          let savePath = ret.savePath;
                          window.api.installApp({
                            appUri: savePath,
                          });
                        }
                        if (ret && ret.state == 2) {
                          window.api.toast({
                            msg: "更新出错",
                            duration: 2000,
                            location: "middle",
                          });
                        }
                      }
                    );
                  }
                }
              );
            } else if (serverVersion < thisVersion) {
              console.log(1);
            }
          }
        } else {
          // window.api.toast({
          //   msg: res.data.data,
          //   duration: 2000,
          //   location: "middle",
          // });
        }
      });
  },
};
</script>

<style scoped lang="scss">
@media screen and (min-width: 320px) and (max-width: 414px) {
  @keyframes bg-move {
    0% {
      background-position-y: 0px;
    }
    50% {
      background-position-y: 100%;
    }
    100% {
      background-position-y: 0%;
    }
  }
  #app {
    ::v-deep .v-application--wrap {
      height: 100vh;
      position: relative;
      background: aquamarine url("../../assets/img/pad-2.jpg") center/120% 120%
        no-repeat;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 1px;
      background-position-y: 0px;
      animation: bg-move 30s infinite;
    }
  }
}

@media screen and (min-width: 415px) {
  @keyframes bg-move {
    0% {
      background-position-y: 0px;
    }
    50% {
      background-position-y: 100%;
    }
    100% {
      background-position-y: 0%;
    }
  }
  #app {
    ::v-deep .v-application--wrap {
      height: 100vh;
      position: relative;
      background: aquamarine url("../../assets/img/pad-2.jpg") center/120% 120%
        no-repeat;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 1px;
      background-position-y: 0px;
      animation: bg-move 30s infinite;
    }
  }
}
::v-deep .v-application .v-application--wrap {
  align-items: center;
}
.login-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  max-width: 92%;
  padding: 20px 10px;
  border-radius: 18px;
  margin: 8vw 0;
  flex-shrink: 0;
  .mu-input,
  .check-box,
  .login-btn {
    width: 80vw;
  }
  .login-btn {
    margin-top: 8vw;
    padding: 20px;
    letter-spacing: 8px;
    background: linear-gradient(225deg, #6279eca1, #193790b7 75%);
  }
  .login-img {
    margin: 6vw 0 8vw;
    img {
      width: 50%;
      margin: 0 auto;
    }
  }
}
.download-modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 24px;
  height: 80vh;
  width: 100vw;
  .linear-progress {
    width: 100%;
  }
  .percent {
    font-size: 12vw;
    color: rgb(76, 175, 80);
  }
}
.langSelected {
  background-color: #eee;
  .mu-item-title {
    color: #2196f3;
  }
}
.login-copyright {
  color: white;
  position: absolute;
  bottom: 5px;
  text-align: center;
  font-size: 12px;
}
.setting {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 20px;
  height: 20px;
  color: #ddd;
}
</style>
